package com.itheima.controller.backend.security;

import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

import static com.itheima.common.constant.RedisConstant.SETMEAL_PIC_RESOURCES;

@RestController
@Slf4j
@RequestMapping("/setmeal")
public class CommonController {


    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/upload")
    public Result<String> upload(@RequestParam("imgFile") MultipartFile file) {
        try {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + extension;

            // 上传到OSS
            String url = aliOssUtil.upload(file.getBytes(), fileName);

            // 将图片名存入Redis集合
            redisTemplate.opsForSet().add(SETMEAL_PIC_RESOURCES, fileName);

            return new Result<>(true,"上传成功",url);
        } catch (Exception e) {
            log.error("图片上传失败", e);
            return new Result<>(false,"图片上传失败");
        }
    }
}